package www.hz.domain.strategy.service.rule.chain.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import www.hz.domain.strategy.model.entity.RuleActionEntity;
import www.hz.domain.strategy.model.vo.RuleLogicCheckTypeVO;
import www.hz.domain.strategy.repository.IStrategyRepository;
import www.hz.domain.strategy.service.armory.IStrategyDispatch;
import www.hz.domain.strategy.service.rule.chain.AbstractLogicChain;
import www.hz.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import www.hz.domain.strategy.service.rule.filter.factory.DefaultLogicFactory;
import www.hz.types.common.Constants;

import javax.annotation.Resource;
import java.util.*;

/**
 * @className: RuleWeightLogicChain
 * @Description: TODO
 * @version: v1.８.0
 * @author: hz
 * @date: 2025/3/16 9:37
 */
@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {
    @Resource
    private IStrategyRepository repository;
    @Resource
    protected IStrategyDispatch strategyDispatch;
    public Long userScore = 4500L;
    @Override
    public String ruleModel() {
        return "rule_weight";
    }

    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        String ruleValue = repository.queryStrategyRuleValue(strategyId,ruleModel());
        Map<Long,String> analyticalValueGroup=getAnalyticalValueGroup(ruleValue);
        //2.找出最小符合的值，也就是【4500 积分，能找到 4000:102,103,104,105】、【5000 积分，能找到 5000:102,103,104,105,106,107】
        List<Long> analyticalSortedKeys=new ArrayList<>(analyticalValueGroup.keySet());
        Collections.sort(analyticalSortedKeys, Comparator.reverseOrder());
        Long nextValue=analyticalSortedKeys.stream().filter(key->userScore>=key).findFirst().orElse(null);
        if(nextValue!=null){
            String awardId=analyticalValueGroup.get(nextValue);
            log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
            return DefaultChainFactory.StrategyAwardVO.builder().awardId(strategyDispatch.getRandomAwardId(strategyId,awardId)).logicModel(DefaultChainFactory.LogicModel.RULE_BLACKLIST.getCode()).build();
        }
        log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        return next().logic(userId,strategyId);
    }
    private Map<Long, String> getAnalyticalValueGroup(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> map=new HashMap<>();
        for (String ruleValueGroup : ruleValueGroups) {
            String[] ruleValueGroupAttr=ruleValueGroup.split(Constants.COLON);
            if (ruleValueGroupAttr.length != 2) throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueGroup);
            map.put(Long.valueOf(ruleValueGroupAttr[0]),ruleValueGroup);
        }
        return map;
    }
}